import axios from 'axios';

var request = {};
var injectors = [];
var receivers = [];
console.log('@util before create');
const instance = axios.create({
  timeout: 2000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  }
});
instance.interceptors.request.use(
  ({ config }) => {
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.headers = JSON.stringify(config.headers);
    }
    // eslint-disable-next-line no-unused-vars
    injectors.forEach((item, index) => {
      console.log('@util before config');
      item(config);
      config.headers = JSON.stringify(config.headers);
    });
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  ({ response }) => {
    // eslint-disable-next-line no-unused-vars
    receivers.forEach((item, index) => {
      console.log('@util before setup receiver');
      item(response);
    });
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);
console.log(request, '==========');
request.setInjector((injector) => {
  console.log('@util ....... setInjector', request, injector);
  console.log('@util before injecting');
  injectors = [injector];
});
request.setReceiver((receiver) => {
  console.log('@util before receiving');
  receivers = [receiver];
});
request.post((url, data, config) => {
  return instance.post(url, data, config);
});
request.get((url, config) => {
  return instance.get(url, config);
});
export default request;
